package org.gongliang.jfinal.common.interceptor;

import java.util.Enumeration;

import org.gongliang.jfinal.common.base.KaptchaRender;
import org.gongliang.jfinal.common.base.Result;
import org.gongliang.jfinal.common.exception.ExceptionEnum;

import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

public class LoginValidate extends Validator{

	@Override
	protected void handleError(Controller c) {
		Result result = Result.error(getFirstErrMsg(c));
		c.keepPara("username");
	
		c.renderJson(result);
	}

	@Override
	protected void validate(Controller c) {
		
		validateRequired("username", "msg1", "请输入您的登陆账号");
		validateRequired("password", "msg2", "请输入您的密码");
		validateString("password", 3, 24, "msg3", "请输入6~24位的密码");
		validateRequired("captcha", "msg4", "请输入验证码");
		validateCaptcha("captcha", "msg5", "验证码错误");
	}

	
	protected void validateCaptcha(String field, String errorKey, String errorMessage) {
		if (!KaptchaRender.validate(getController(), field))
			addError(errorKey, errorMessage);
	}
	
	//获取错误信息
	public static String getFirstErrMsg(Controller c) {
        StringBuffer errorString = new StringBuffer("");
        Enumeration<String> attrNames = c.getAttrNames();
        String wrongAtrrs = "msg1msg2msg3msg4msg5";
        //获取第一个错误属性key
        if (attrNames != null) {
            while (attrNames.hasMoreElements()) {
                String attrName = attrNames.nextElement();
                if(wrongAtrrs.contains(attrName)) {
                	errorString.append(c.getAttrForStr(attrName)+"!");
                	break;
                }
                
            }
        }
       

        return errorString.toString();
    }
}
